/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.sound {
	
	/**
	 * SoundTrack: Contains and controls a collection of sounds.
	 * @author Dale J Williams
	 * @version 1.0
	 */
	public class SoundTrack {
		
		private var _name			:String;
		private var _sounds			:Vector.<SoundObject>;
		
		private var _volume			:Number;
		private var _volumeAbs		:Number;
		
		private var _manager		:SoundManager;
		
		private var _numChannels	:int;
		private var _fadeTime		:Number;
		
		public function SoundTrack($name:String, $numChannels:int=-1, $fadeTime:Number=0, $volume:Number=1) {
			_name = $name;
			_numChannels = $numChannels;
			_fadeTime = $fadeTime;
			_volume = _volumeAbs = $volume;
			init();
		}
		
		private function init():void {
			_sounds = new Vector.<SoundObject>();
		}
		
		public function playSound($sound:SoundObject):void {
			if ($sound.track == this && $sound.playing && $sound.looping) {
				$sound.cancelFade();
				return;
			}
			_sounds.push($sound);
			if (_numChannels > 0 && _sounds.length > _numChannels)
				stopSound(_sounds.shift());
			$sound.track = this;
			$sound.rewind();
			$sound.play();
		}
		
		public function stopSound($sound:SoundObject, $hardStop:Boolean = false):void {
			if (!$hardStop && _fadeTime > 0)
				$sound.fadeOut(_fadeTime);
			else {
				$sound.stop();
				var i:int = _sounds.length;
				while (i--) 
					if (_sounds[i] == $sound)
						_sounds.splice(i, 1);
			}
		}
		
		public function stopAllSounds($hardStop:Boolean=false):void {
			for each(var sound:SoundObject in _sounds)
				stopSound(sound, $hardStop);
		}
		
		public function updateVolume():void {
			_volumeAbs = _volume * _manager.volume;
			for each(var sound:SoundObject in _sounds)
				sound.updateVolume();
		}
		
		public function get name():String { return _name; }		
		
		public function get volume():Number { return _volume; }		
		public function set volume(value:Number):void {
			_volume = value;
			updateVolume();
		}
		
		public function get manager():SoundManager { return _manager; }		
		public function set manager(value:SoundManager):void {
			_manager = value;
			updateVolume();
		}
		
		public function get volumeAbs():Number { return _volumeAbs; }
		
		public function get sounds():Vector.<SoundObject> { return _sounds; }
		
	}

}